<?php

namespace App\Http\Controllers\Tenant;

use Validator;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\QingShanERP\Shop;
use App\Http\Controllers\Controller;
use App\Models\Tenant\ShopToShop;
use Illuminate\Support\Facades\DB;

class ShopController extends Controller
{
    public function getList(Request $request)
    {
        try {
            $page = $request->input('page', 0);
            $size = $request->input('size', 10);
            $type = $request->input('type', 0);
            $status = $request->input('status', '');
            $key = $request->input('key', '');
            $tenant_id = $request->tenant->tid;
            $list = Shop::where('tenant_id', $tenant_id)->where(function ($q) use ($type) {
                if ($type != 0) {
                    $q->where('type', $type);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('shopname', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($status) {
                if ($status != '') {
                    $q->where('status', $status);
                }
            })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('id', 'desc')->get();
            $count = Shop::where('tenant_id', $tenant_id)->where(function ($q) use ($type) {
                if ($type != 0) {
                    $q->where('type', $type);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('shopname', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($status) {
                if ($status != '') {
                    $q->where('status', $status);
                }
            })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }

    public function postCreate(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'type' => 'required|in:1,2,3,4',
                'shopname' => 'required|max:20',
                'shopid' => 'required|max:100'
            ]);
            $attrs = array(
                'type' => '类型',
                'shopname' => '店铺名',
                'shopid' => '店铺ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $create = ['tenant_id' => $request->tenant->tid, 'type' => $all['type'], 'shopname' => $all['shopname'], 'shopid' => $all['shopid'],'crypt' => 'VGSzMNulh6','password' => '03966752031094278983af0057dc7cdb', 'status' => 1];
            Shop::create($create);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加文章失败，请重新操作...');
        }
    }
    //详情
    public function postDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'shop_id' => 'required',
            ]);
            $attrs = array(
                'shop_id' => '店铺ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('shop_id');
            $info = Shop::find($id);
            return $this->resData(200, '获取数据成功...', $info);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请重新操作...');
        }
    }
    //编辑
    public function postEdit(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'shop_id' => 'required',
                'type' => 'required|in:1,2,3,4',
                'shopname' => 'required|max:20',
                'shopid' => 'required|max:100',
                'status' => 'required|in:true,false',
            ]);
            $attrs = array(
                'shop_id' => '店铺ID',
                'type' => '类型',
                'shopname' => '店铺名',
                'shopid' => '店铺ID',
                'status' => '状态',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('shop_id');
            $all = $request->all();
            $update = ['type' => $all['type'], 'shopname' => $all['shopname'], 'shopid' => $all['shopid'], 'status' => $all['status'] == 'true' ? 1 : 0];
            Shop::where('id', $id)->update($update);
            return $this->resData(200, '编辑成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '编辑失败，请重新操作...');
        }
    }

    // 删除
    public function postRemove(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'shop_id' => 'required|array',
            ]);
            $attrs = array(
                'shop_id' => '店铺ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('shop_id');
            if (!is_null(Shop::whereIn('id', $id)->where('super_flag', 1)->first())) {
                return $this->resData(400, '有租户创建者，不允许删除...');
            }
            $tenant_id = $request->tenant->tid;
            Shop::where('tenant_id', $tenant_id)->whereIn('id', $id)->update(['del_flag' => 1]);
            return $this->resData(200, '删除成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '删除失败，请重新操作...');
        }
    }
    // 处理门店关联管理关系
    public function getShopRelation(Request $request){
        try {
            $validator = Validator::make($request->input(), [
                'shop_id' => 'required',
            ]);
            $attrs = array(
                'shop_id' => '店铺ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('shop_id');
            $shop2 = ShopToShop::where('shop_id',$id)->pluck('shop2_id')->toArray();
            $list = Shop::where('tenant_id', $request->tenant->tid)->where('del_flag', 0)->orderBy('id', 'desc')->get();
            // 循环加入是否选中
            foreach ($list as $k => $v) {
                if (in_array($v['id'],$shop2)) {
                    $v['_checked'] = true;
                }
                else {
                    $v['_checked'] = false;
                }
                $list[$k] = $v;
            }
            return $this->resData(200, '获取数据成功...', $list);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请重新操作...');
        }
    }
    public function postShopRelation(Request $request){
        DB::beginTransaction();
        try {
            if (!$request->tenant->super) {
                DB::rollBack();
                return $this->resData(400, '此账户无管理权限...');
            }
            $validator = Validator::make($request->input(), [
                'shop_id' => 'required',
                'shop2_id' => 'required|array',
            ]);
            $attrs = array(
                'shop_id' => '店铺ID',
                'shop2_id' => '被绑定门店',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                DB::rollBack();
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('shop_id');
            ShopToShop::where('shop_id', $id)->delete();
            $shop2 = $request->input('shop2_id');
            $insert = [];
            foreach ($shop2 as $s) {
                $insert[] = ['shop_id'=>$id,'shop2_id'=>$s];
            }
            ShopToShop::insert($insert);
            DB::commit();
            return $this->resData(200, '修改数据成功...');
        } catch (\Throwable $e) {
            DB::rollBack();
            return $this->resData(500, '修改数据失败，请重新操作...');
        }
    }
    // 查退货地址库 pdd.refund.address.list.get 获取商家退货地址库
    public function getAddressList(Request $request)
    {
        $shopid = $request->input('shopid', 0);
        $params['access_token'] = PddRequest::getToken($shopid);
        if (is_null($params['access_token'])) {
            return $this->resData(400, '此门店授权已过期，请先重新授权...');
        }
        $result = PddRequest::request('pdd.refund.address.list.get', $params);
        return $this->resData(200, '成功...', $result);
    }
}
